package com.core.gig.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.core.as.ASException;
import com.core.gig.as.ASConfiguracao;
import com.core.gig.as.ASFactory;
import com.core.gig.as.ASSeguranca;
import com.core.gig.dto.UsuarioDTO;
import com.core.gig.util.GIGUtil;

/**
 * @author Lucas Ceni
 *
 */
public class UsuarioAction
		extends GIGAction
{
	@Override
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		return listar(mapping, form, request, response);
	}

	public ActionForward incluir(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		clearForm(form);
		return mapping.findForward(FWD_DEFAULT);
	}
	
	public ActionForward salvar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		UsuarioDTO dto = new UsuarioDTO();
		GIGUtil.copyProperties(dto, form);
		
		try
		{
			ASSeguranca as = ASFactory.getInstance().getASSeguranca();
			as.salvarUsuario(dto);
			
			addMessage(request, "global.msg.sucess.inclusion", ICO_OK);
			return listar(mapping, form, request, response);
		}
		catch (ASException e)
		{
			addMessage(request, e.getMessage(), ICO_ERROR);
			return incluir(mapping, form, request, response);
		}
	}
	
	public ActionForward listar(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			ASConfiguracao asConfiguracao = ASFactory.getInstance().getASConfiguracao();
			ASSeguranca asSeguranca = ASFactory.getInstance().getASSeguranca();
			UsuarioDTO adm = asConfiguracao.recuperarAdministrador();
			
			request.setAttribute("adm", adm);
			request.setAttribute("usuarios", asSeguranca.listarUsuarios());
		}
		catch (ASException e)
		{
			addMessage(request, e.getMessage(), ICO_ERROR);
		}
		return mapping.findForward(FWD_LIST);
	}
	
	public ActionForward excluir(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
	{
		int id = id(form);
		if (getCredential(request).getId() == id)
		{
			addMessage(request, "uc007.msg.alert.1", ICO_ALERT);
			return listar(mapping, form, request, response);
		}
		
		UsuarioDTO dto = new UsuarioDTO();
		dto.setId(id);
		
		try
		{
			ASSeguranca as = ASFactory.getInstance().getASSeguranca();
			as.excluirUsuario(dto);
			addMessage(request, "global.msg.sucess.exclusion", ICO_OK);
		}
		catch (ASException e)
		{
			addMessage(request, e.getMessage(), ICO_ERROR);
		}
		return listar(mapping, form, request, response);
	}
}